# -*- coding: utf-8 -*-
"""
Created on Mon Jun 17 14:00:53 2013

@author: Maxim
"""
import os
from numpy import zeros,array,linspace
import matplotlib.pyplot as plt
import aircraft
import aerodynamics
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

class WTresult:
    def __init__(self,path=None):
        n = 20
        self.name  = 'results'
        self.alpha = zeros(n)
        self.beta  = zeros(n)
        self.CL    = zeros(n)
        self.CD    = zeros(n)
        self.CY    = zeros(n)
        self.CM    = zeros(n)
        self.CN    = zeros(n)
        self.CR    = zeros(n) # cl - rolling moment
        self.LD    = zeros(n)
        self.Ho    = zeros(n)
        self.V     = zeros(n)
        self.P     = zeros(n)
        self.Q     = zeros(n)
        self.T     = zeros(n)
        self.M     = zeros(n)
        self.Re    = zeros(n)
        if not path==None:
            if type(path)==type(int()):
                path = find_file_by_number(path)
                self._read_wt(path)
            elif type(path)==type(str()):
                self._read_wt(path)
    def _read_wt(self,path):
        fid = open(path,'rt')
        for i in range(13): fid.readline()
        line = fid.readline()
        while line.strip()!='':
            seg = line.split()
            i = int(seg[0])-1
            self.alpha[i] = float(seg[1])
            self.beta[i]  = float(seg[2])
            self.CL[i]    = float(seg[3])
            self.CD[i]    = float(seg[4])
            self.CY[i]    = float(seg[5])
            self.CM[i]    = float(seg[6])
            self.CN[i]    = float(seg[7])
            self.CR[i]    = float(seg[8])
            self.LD[i]    = float(seg[9])
            self.Ho[i]    = float(seg[10])*1000.
            self.V[i]     = float(seg[11])
            self.P[i]     = float(seg[12])*1000.
            self.Q[i]     = float(seg[13])*1000.
            self.T[i]     = float(seg[14])
            self.M[i]     = float(seg[15])
            self.Re[i]    = float(seg[16])*1.0e6
            line = fid.readline()
        self._clean_arrays(i+1)
    def _clean_arrays(self,imax):
        self.alpha = self.alpha[:imax]
        self.beta  = self.beta[:imax]
        self.CL    = self.CL[:imax]
        self.CD    = self.CD[:imax]
        self.CY    = self.CY[:imax]
        self.CM    = self.CM[:imax]
        self.CN    = self.CN[:imax]
        self.CR    = self.CR[:imax] # cl - rollimaxng moment
        self.LD    = self.LD[:imax]
        self.Ho    = self.Ho[:imax]
        self.V     = self.V[:imax]
        self.P     = self.P[:imax]
        self.Q     = self.Q[:imax]
        self.T     = self.T[:imax]
        self.M     = self.M[:imax]
        self.Re    = self.Re[:imax]
    def _read_vlm_results(self,results):
        imax = len(results)
        for i in range(imax):
            self.alpha[i] = results[i].alpha
            self.beta[i] = results[i].beta
            self.CL[i] = results[i].coefficients.CL
            self.CD[i] = results[i].coefficients.CD
            self.CY[i] = results[i].coefficients.CY
            self.CM[i] = results[i].coefficients.Cm
            self.CN[i] = results[i].coefficients.Cn
            self.CR[i] = results[i].coefficients.Cl
            self.LD[i] = self.CL[i] / self.CD[i]
            #self.V[i] = results[i].velocity
        self._clean_arrays(imax)


def compare_results(rslt1,rslt2):
    plt.figure(1)
    plt.grid(True)
    plt.hold(True)
    plt.ylabel('lift coef.')
    plt.xlabel('AoA, deg')
    plt.plot(rslt1.alpha,rslt1.CL,'ro-')
    plt.plot(rslt2.alpha,rslt2.CL,'bs-')
    plt.legend(['Experiment','Computed'],0)
    plt.figure(2)
    plt.grid(True)
    plt.hold(True)
    plt.xlabel('AoA, deg')
    plt.ylabel('drag coef.')
    plt.plot(rslt1.alpha,rslt1.CD,'ro-')
    plt.plot(rslt2.alpha,rslt2.CD,'bs-')
    plt.legend(['Experiment','Computed'],0)
    plt.figure(3)
    plt.grid(True)
    plt.hold(True)
    plt.xlabel('AoA, deg')
    plt.ylabel('pitching moment coef.')
    plt.plot(rslt1.alpha,rslt1.CM,'ro-')
    plt.plot(rslt2.alpha,rslt2.CM,'bs-')
    plt.legend(['Experiment','Computed'],0)
    plt.figure(4)
    plt.grid(True)
    plt.hold(True)
    plt.xlabel('AoA, deg')
    plt.ylabel('rolling moment coef.')
    plt.plot(rslt1.alpha,rslt1.CR,'ro-')
    plt.plot(rslt2.alpha,rslt2.CR,'bs-')
    plt.legend(['Experiment','Computed'],0)
    plt.figure(5)
    plt.grid(True)
    plt.hold(True)
    plt.xlabel('AoA, deg')
    plt.ylabel('yawing moment coef.')
    plt.plot(rslt1.alpha,rslt1.CN,'ro-')
    plt.plot(rslt2.alpha,rslt2.CN,'bs-')
    plt.legend(['Experiment','Computed'],0)
    plt.show()

def find_file_by_number(n,wdir=None):
    if wdir==None:
        wdir = r'D:\light aircraft\V05\Wind tunnel results processing\wind tunnel tests\results'
    for r,d,f in os.walk(wdir):
        for files in f:
            if int(files[7:10])==int(n):
                return os.path.join(r,files)
    else:
        return None

def run_clean_configuration():
    ac = aircraft.load('V0510')
    CG = ac.get_CG()
    CG = [1.711,0.0,-0.104]
    I = ac.get_inertia()
    m = ac.get_mass_total()
    V = 34.0
    rho = 1.2255
    CD0 = ac.get_drag(V,0.0)
    aero3d = aerodynamics.aero3d_VLM(ac)

    case = [9,10,11]
    alpha = array([-2,0.0,2,4,6,8,10,12])
    beta = array([0.0,10.0,20.0])
    wtRslt = list()
    avlRslt = list()

    for i in range(len(case)):
        fc = aerodynamics.flightConditions()
        b = beta[i]
        for a in alpha:
            fc.add_flight_condition('wt validation',m,CG,I,V,rho,CD0=CD0,alpha=a,beta=b)
        wtPath = find_file_by_number(case[i])
        wtRslt.append(WTresult(wtPath))
        _avlrslt = aero3d.runVLM(fc).results
        _avlRslt = WTresult()
        _avlRslt._read_vlm_results(_avlrslt)
        avlRslt.append(_avlRslt)
        compare_results(wtRslt[i],avlRslt[i])

def func_01():
    #case = [9,78,82,86,90,94,99]
    case = [22]
    
    rslt = list()
    for c in case:
        wtPath = find_file_by_number(c)
        rslt.append(WTresult(wtPath))
    
    fig = plt.figure(1)
    ax1 = fig.add_subplot(211)
    ax1.grid(True)
    ax1.set_title('Flap 35deg')
    ax1.hold(True)
    ax1.plot(rslt[0].alpha,rslt[0].CL,'bo-')
    ax1.set_xlabel('AOA, deg')
    ax1.set_ylabel('CL')
    ax2 = ax1.twinx()
    ax2.plot(rslt[0].alpha,rslt[0].CM,'ro-')
    ax2.set_ylabel('CM')
    
    ax3 = fig.add_subplot(212)
    ax3.grid(True)
    ax3.hold(True)
    ax3.plot(rslt[0].alpha,rslt[0].CR,'ko-')
    ax3.set_xlabel('AOA,deg')
    ax3.set_ylabel('Cl\'')
    
#    ax4 = fig.add_subplot(313)
#    ax4.hold(True)
#    ax4.grid(True)
#    for i in range(len(case)-1):
#        ax4.plot(rslt[i+1].alpha,rslt[i+1].CR,'o-')
#    ax4.set_xlabel('AOA,deg')
#    ax4.set_ylabel('Cl\'ail')
#    ax4.legend(['AIL20','AIL16','AIL12','AIL12','AIL8'],'upper left')
#    
    ax1.set_axes([-1.0,1.5])
    ax1.xaxis.set_major_locator(MultipleLocator(10))
    ax1.xaxis.set_major_formatter(FormatStrFormatter('%d'))
    ax1.xaxis.set_minor_locator(MultipleLocator(1))
    
    ax1.yaxis.set_major_locator(MultipleLocator(1.0))
    ax1.yaxis.set_minor_locator(MultipleLocator(0.25))
    
    ax1.xaxis.grid(True,'minor')
    ax1.yaxis.grid(True,'minor')
    ax1.xaxis.grid(True,'major',linewidth=1.5)
    ax1.yaxis.grid(True,'major',linewidth=1.5)
    ##
    ax3.xaxis.set_major_locator(MultipleLocator(10))
    ax3.xaxis.set_major_formatter(FormatStrFormatter('%d'))
    ax3.xaxis.set_minor_locator(MultipleLocator(1))
    
    #ax3.yaxis.set_major_locator(MultipleLocator(0.01))
    #ax3.yaxis.set_minor_locator(MultipleLocator(0.005))
    
    ax3.xaxis.grid(True,'minor')
    ax3.yaxis.grid(True,'minor')
    ax3.xaxis.grid(True,'major',linewidth=1.5)
    ax3.yaxis.grid(True,'major',linewidth=1.5)
    ##
#    ax4.xaxis.set_major_locator(MultipleLocator(10))
#    ax4.xaxis.set_major_formatter(FormatStrFormatter('%d'))
#    ax4.xaxis.set_minor_locator(MultipleLocator(1))
#    
#    ax4.yaxis.set_major_locator(MultipleLocator(0.01))
#    ax4.yaxis.set_minor_locator(MultipleLocator(0.005))
#    
#    ax4.xaxis.grid(True,'minor')
#    ax4.yaxis.grid(True,'minor')
#    ax4.xaxis.grid(True,'major',linewidth=2)
#    ax4.yaxis.grid(True,'major',linewidth=2)
    plt.show()

def test_02():
    rslt1 = WTresult(find_file_by_number(31))
    rslt2 = WTresult(find_file_by_number(30))
    print rslt1.alpha
    print rslt1.CL

    plt.hold(True)
    plt.grid(True)
    plt.plot(rslt1.CD,rslt1.CL)
    plt.plot(rslt2.CD,rslt2.CL)
    plt.show()
    
if __name__=="__main__":
    test_02()